package com.tjb.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author tjb
 * @version 1.0
 * @date 2022/8/24 20:57
 * 全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 异常处理方法
     *
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        if (exception.getMessage().contains("Duplicate entry")){
            String[] splits = exception.getMessage().split(" ");
            String message = splits[2] + "已存在";
            return R.error(message);
        }
        return R.error(exception.getStackTrace()[0].getMethodName()+":"+exception.getStackTrace()[0].getLineNumber());
    }

    /**
     * 自定义异常处理
     * @param exception
     * @return
     */
    @ExceptionHandler(TjbException.class)
    public R<String> exceptionHandler(TjbException exception){
        return R.error(exception.getMessage());
    }
}
